package com.google.code.twiddling.core.context;

import com.google.code.twiddling.core.bootstrap.TwiddlingShell;
import com.google.code.twiddling.core.util.PreferencesUtil;

import java.util.prefs.Preferences;

/**
 * Store variables value into file system that was provided by <code>java.util.pref.Preference</code>
 * 
 * @author <a href="mailto:yy.young@gmail.com">Young Yang</a>
 * @author <a href="mailto:jeff.yuchang@gmail.com">Jeff Yu</a>
 * 
 */
public class PersistenceableEnvironment extends DefaultEnvironment{

    private static final Preferences ENV_PREFERENCES = PreferencesUtil.getTwiddlingPreferences().node("env");

    public PersistenceableEnvironment() {
        super();
    }
    
    public PersistenceableEnvironment(TwiddlingShell shell) {
    	super(shell);
    }

    @Override
    public void activate() {
        super.activate();
    }

    @Override
    public void deactivate() {
        super.deactivate();
        try {
            ENV_PREFERENCES.clear();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setProfile(Profile profile) {
        super.setProfile(profile);

        for(String key : keys()) {
            ENV_PREFERENCES.put(key, getVariable(key));
        }
        
    }

    @Override
    public void setVariable(String name, String value) {
        super.setVariable(name, value);
        ENV_PREFERENCES.put(name,value);
        flushPreferences();
    }
    
    @Override
    public String getVariable(String name) {
    	String val = super.getVariable(name);
    	if (val == null) {
    		val = ENV_PREFERENCES.get(name, null);
    	}
    	return val;
    }

    @Override
    public void removeVariable(String name) {
        super.removeVariable(name);
        flushPreferences();
    }

    private void flushPreferences() {
        try {
            ENV_PREFERENCES.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
